package com.youbu.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * @author sunfangwei
 **/
public class SQLDemo {

	// JDBC 驱动名及数据库 URL
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://192.168.4.224:3306/spark_demo2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";

	// 数据库的用户名与密码，需要根据自己的设置
	static final String USER = "root";
	static final String PASS = "root";

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try {
			// 注册 JDBC 驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 打开链接
			System.out.println("连接数据库...");
			conn = DriverManager.getConnection(DB_URL, USER, PASS);

			// 执行查询
			System.out.println(" 实例化Statement对象...");
			stmt = conn.createStatement();
			String sql;
			sql = "INSERT INTO integral_use_record_tab(id,userId,amount) VALUES";
			int n = 30000000;
			//产生随机数据，写入文件
			Random random = new Random();
			int i=1;
			String sqlStr = sql;
			while (i<=n){
				int userId = (int) Math.floor((random.nextDouble() * 100.0));
				int randint = -5+(int)(Math.random()*(10-(-5)+1));

				if(i % 1000 == 0){
					sqlStr += "('X" + UUID.randomUUID() + "'," + userId + "," + randint + ")";
					stmt.execute(sqlStr);
					System.out.println(new Date()+"插入数据......");
					sqlStr = sql;
				}else {
					sqlStr += "('X" + UUID.randomUUID() + "'," + userId + "," + randint + "),";
				}
				i++;
			}


			// 完成后关闭

			stmt.close();
			conn.close();
		} catch (SQLException se) {
			// 处理 JDBC 错误
			se.printStackTrace();
		} catch (Exception e) {
			// 处理 Class.forName 错误
			e.printStackTrace();
		} finally {
			// 关闭资源
			try {
				if (stmt != null) {
					stmt.close();
				}
			} catch (SQLException se2) {
			}// 什么都不做
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
		System.out.println("Goodbye!");
	}
}
